<?php

namespace app\admin\controller\newhouse;

use app\common\controller\Backend;

/**
 * 新房户型管理
 *
 * @icon fa fa-circle-o
 */
class Layout extends Backend
{

    /**
     * NewhouseLayout模型对象
     * @var \app\common\model\NewhouseLayout
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model    = new \app\common\model\NewhouseLayout;
        $newhouse_id    = input('newhouse_id', '');
        $structure_id   = input('structure_id', '');
        $building_id    = input('building_id', '');
        $structure      = model('newhouse_structure')->get($structure_id);
        $this->view->assign("category", $structure['category_id']);
        $this->view->assign("newhouse_id", $newhouse_id);
        $this->view->assign("structure_id", $structure_id);
        $this->view->assign("building_id", $building_id);
        $this->view->assign("htypeList", $this->model->getHtypeList());
        $this->view->assign("vtypeList", $this->model->getVtypeList());
        $this->view->assign("atypeList", $this->model->getAtypeList());
        $this->view->assign("stypeList", $this->model->getStypeList());
        $this->view->assign("otypeList", $this->model->getOtypeList());
        $this->view->assign("recommendList", $this->model->getRecommendList());
        $this->view->assign("flagList", $this->model->getFlagList());
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                    ->with(['admin','newhousestructure'])
                    ->where($where)
                    ->order($sort, $order)
                    ->count();

            $list = $this->model
                    ->with(['admin','newhousestructure'])
                    ->where($where)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();

            foreach ($list as $row) {
                $row->visible(['id','title','url','htype','vtype','atype','stype','otype','floorage','innerarea','usearea','recommend','flag','createtime','updatetime']);
                $row->visible(['admin']);
				$row->getRelation('admin')->visible(['nickname']);
                $row->visible(['newhousestructure']);
                $row->getRelation('newhousestructure')->visible(['category_id']);
            }
            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if ($ids) {
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $count = $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model->where($pk, 'in', $ids)->select();
            $count = 0;
            foreach ($list as $k => $v) {
                // 删除图片
                $arr = explode(',', $v['url']);
                if ($arr) {
                    foreach ($arr as $kk => $vv) {
                        $attachmentFile = ROOT_PATH . '/public/uploads' . $vv;
                        if (is_file($attachmentFile))
                        {
                            @unlink($attachmentFile);
                        }
                        //同步删除oss
                        $ftpcfg = get_addon_config('ftp');
                        if ($ftpcfg['ftp_usernmae'] && $ftpcfg['ftp_password']) {
                            $FTP = new \addons\ftp\library\Auth($ftpcfg['ftp_host'], $ftpcfg['ftp_port'], $ftpcfg['ftp_usernmae'], $ftpcfg['ftp_password'], $ftpcfg['ftp_ssh'], $ftpcfg['ftp_pasv']);
                            $FTP->del_file(str_replace('/', DIRECTORY_SEPARATOR, $vv));
                            $FTP->close();
                        }
                    }
                }

                $count += $v->delete();
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }

    /**
     * 删除户型图片
     */
    public function delUpload()
    {
        if ($this->request->isPost()) {
            $path = input('path');
            $attachmentFile = ROOT_PATH . '/public/uploads' . $path;
            if (is_file($attachmentFile))
            {
                @unlink($attachmentFile);
            }
            //同步删除oss
            $ftpcfg = get_addon_config('ftp');
            if ($ftpcfg['ftp_usernmae'] && $ftpcfg['ftp_password']) {
                $FTP = new \addons\ftp\library\Auth($ftpcfg['ftp_host'], $ftpcfg['ftp_port'], $ftpcfg['ftp_usernmae'], $ftpcfg['ftp_password'], $ftpcfg['ftp_ssh'], $ftpcfg['ftp_pasv']);
                $FTP->del_file(str_replace('/', DIRECTORY_SEPARATOR, $path));
                $FTP->close();
            }
            $this->success();
        }
    }

    /**
     * 同步价钱
     */
    public function syncPrice()
    {
        $list = $this->model->where('price', null)->select();
        if ($list) {
            $newhouse_structure = model('newhouse_structure');
            $newhouse_price = model('newhouse_price');
            foreach ($list as $item) {
                $structure = $newhouse_structure->where('id', $item['structure_id'])->find();
                $price = $newhouse_price->where('newhouse_id', $item['newhouse_id'])->where('lx', $this->fixLx($structure['category_id']))->order('updatetime desc')->find();
                if ($price['pay2']) {
                    $_post['price'] = $price['pay2'];
                    $this->model->where('id', $item['id'])->update($_post);
                }
            }
        }

    }

    private function fixLx($val)
    {
        $lx = 0;
        switch ($val) {
            case '1':
                $lx = 0; // 住宅
                break;
            case '6':
                $lx = 1; // 商铺
                break;
            case '3':
                $lx = 2; // 公寓
                break;
            case '7':
                $lx = 3; // 别墅
                break;
            case '4':
                $lx = 4; // 写字楼
                break;
        }
        return $lx;
    }
}
